import XLSX from 'xlsx';

/**
 * 处理错误的函数 主线程可以监听 Worker 是否发生错误。
 * 如果发生错误，Worker 会触发主线程的`error`事件。
 */
const ERROR = () => {
    // 发送错误信息
    self.postMessage({message: 'error', data: []})
    self.close()
}

// 错误处理
self.addEventListener('error', (event) => {
    ERROR()
    // 输出错误信息
    console.log('ERROR: Line ', event.lineno, ' in ', event.filename, ': ', event.message)
})
self.addEventListener('message', async (event) => {
    await parseExcel(event.data)
}, false)

const parseExcel = async (data) => {
    const dataBinary = await new Promise(resolve => {
        // Web API构造函数FileReader，可实例化对象，去调用其身上方法，去读取解析文件信息
        console.log('---------****26*****-------', data)
        const reader = new FileReader()
        reader.readAsBinaryString(data)
        reader.onload = ev => {
            resolve(ev.target.result) // 将解析好的结果扔出去，以供使用
        }
    })
    console.log('-----------32-----------', XLSX)
    console.log('-----------33-----------', dataBinary)
    const workBook = XLSX.read(dataBinary, {type: 'binary'})
    console.log('-----------35-----------', workBook)
    let result = [];
    for (let i = 0; i < workBook.SheetNames.length; i++) {
        let item = {
            routeNo: '',
            mainChargeList: []
        };
        const firstWorkSheet = workBook.Sheets[workBook.SheetNames[i]]
        // 分为第一行的数据，和第一行下方的数据
        const header = getHeaderRow(firstWorkSheet)
        console.log("读取的excel表头数据（第一行）", header);
        item.routeNo = header[14];
        const data = XLSX.utils.sheet_to_json(firstWorkSheet);
        item.mainChargeList = data.map(it => {
            return {
                weightVolumeStart: it['GW/Vol_start'] || '',
                weightVolumeEnd: it['GW/Vol_end'] || '',
                currencyCode: it['Currency'] || '',
                minPrice: it['M'] || null,
                firstPrice: it['N'] || null,
                secondaryPrice: it['45+'] || null,
                thirdPrice: it['100+'] || null,
                fourthPrice: it['300+'] || null,
                fifthPrice: it['500+'] || null,
                lastPrice: it['1000+']|| null
            }
        })
        result.push(item);
    }
    self.postMessage(result)
}

const getHeaderRow = sheet => {
    // 定义数组，用于存放解析好的数据
    const headers = []
    // 读取sheet的单元格数据
    const range = XLSX.utils.decode_range(sheet['!ref'])
    let C;
    const R = range.s.r
    for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({c: C, r: R})]
        /* find the cell in the first row */
        // <-- replace with your desired default
        let hdr = 'UNKNOWN ' + C
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
    }
    return headers
}